import socket
import time


def recv_timeout(the_socket, timeout=2):
    the_socket.setblocking(0)
    total_data = []
    data = ""
    begin = time.time()
    while 1:
        if total_data and time.time() - begin > timeout:
            break
        elif time.time() - begin > timeout * 2:
            break

        try:
            data = the_socket.recv(1024)
            if data:
                total_data.append(data)
                begin = time.time()
            else:
                time.sleep(0.1)
        except:
            pass

    the_socket.setblocking(1)
    return ''.join(total_data)


s = socket.socket()

host = socket.gethostname()
port = 1234

s.connect((host, port))
print s.recv(1024)

while True:
    try:
        cmd = raw_input(">")
    except(KeyboardInterrupt) as e:
        print e
        break
    if cmd:
        s.sendall(cmd + '\n')
        data = recv_timeout(s, 0.2)
        print data
        if(cmd == "quit"):
            break
